import connector.DATAbaseDriver



class FoodDao:
    def __init__(self):
        try:
            self.driver = connector.DATAbaseDriver.DatabaseDriver()
        except Exception as e:
            print(f"Error initializing DatabaseDriver: {e}")
            self.driver = None

    def insert_food(self, food_id,food_name, food_price, food_type):
        if self.driver is None:
            print("Driver not initialized")
            return
        sql = f"INSERT INTO food (food_id, food_name, food_prize, food_type) VALUES ('{food_id}','{food_name}', {food_price}, '{food_type}')"
        return self.driver.insert(sql, log=True)

    def search_food_by_name(self, food_id: int) -> tuple:
        if self.driver is None:
            print("Driver not initialized")
            return ()
        sql = f"SELECT * FROM food WHERE food_id = '{food_id}'"
        return self.driver.select_all(sql, log=True)

    def get_all_food(self) -> list:
        if self.driver is None:
            print("Driver not initialized")
            return []
        sql = 'SELECT * FROM food'
        return self.driver.select_all(sql, log=True)

    def update_food(self, food_id: int, food_name: str, food_price: int, food_type: str):
        if self.driver is None:
            print("Driver not initialized")
            return
        sql = f"UPDATE food SET food_name='{food_name}', food_price='{food_price}', food_type='{food_type}' WHERE food_id='{food_id}'"
        try:
            self.driver.execute(sql, log=True)
            print("更新成功")
        except Exception as e:
            print(f"更新食物时出错: {e}")

    # 与对象关联的数据库连接上执行给定的SQL查询，并返回受影响的行数
    def delete_food(self, food_id: int) -> int:
        if self.driver is None:
            print("Driver not initialized")
            return 0
        sql = f"DELETE FROM food WHERE food_id='{food_id}'"
        try:
            # 执行SQL语句，并返回受影响的行数
            affected_rows = self.driver.execute(sql, log=True)
            return affected_rows
        # 捕获异常
        except Exception as e:
            # 如果执行过程中发生异常，打印错误信息并返回0
            print(f"删除食物时出错: {e}")
            return 0
